package cn.ymz.view;


import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ymz.App;
import cn.ymz.component.FxDialogs;
import cn.ymz.observe.Observe;
import cn.ymz.service.CallService;
import cn.ymz.service.impl.CallServiceImpl;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observer;

public class CallViewController {

    private static final Log log = LogFactory.get();

    private App mainApp;

    CallService callService = CallServiceImpl.getInstance();

    public void setMainApp(App mainApp) {
        this.mainApp = mainApp;
    }

    List<Map<String, Object>> callTypeRes;

    @FXML
    private ComboBox<String> callTypes;

    @FXML
    private TextArea textArea;

    @FXML
    private void initialize() {
        Observe observe = Observe.getInstance();
        observe.setTextArea(textArea);

        callTypeRes = callService.getCallType();
        List<String> keys = new ArrayList<>();
        for (Map<String, Object> callTypeRe : callTypeRes) {
            String typeName = String.valueOf(callTypeRe.get("type_name"));
            keys.add(typeName);
        }
        callTypes.getItems().addAll(keys);
        try {
            FileReader reader = new FileReader("CallType.lmt");
            String type = reader.readString();
            if (!StrUtil.isEmpty(type)) {
                for (Map<String, Object> callTypeRe : callTypeRes) {
                    if (type.equals(callTypeRe.get("value") + "")) {
                        callTypes.getSelectionModel().select((String) callTypeRe.get("type_name"));
                    }
                }
            }
        } catch (Exception ignored) {

        }
    }

    @FXML
    private void handleConfirm() {
        System.out.println(callTypes);
        String selected = (String) callTypes.getSelectionModel().getSelectedItem();
        for (Map<String, Object> callTypeRe : callTypeRes) {
            if (ObjectUtil.equal(selected, callTypeRe.get("type_name"))) {
                Integer value = (Integer) callTypeRe.get("value");
                FileWriter writer = new FileWriter("CallType.lmt");
                writer.write(value + "");
                break;
            }
        }
        FxDialogs.showInformation("保存成功", "保存成功，请保持程序后台执行");
    }

}
